package com.fzshang.api.controller;


import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fzshang.commen.bean.*;
import com.fzshang.commen.bean.layuiBean.ResultPage;
import com.fzshang.commen.bean.layuiBean.VoPage;
import com.fzshang.commen.controller.BaseController;
import com.fzshang.commen.entity.ApiResult;
import com.fzshang.commen.util.exception.CommonException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 冯政尚
 * @since 2020-01-28
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    /**
     * @return 登陆
     */
    @RequestMapping(value = "login.html")
    public String login(){
        return "login";
    }

    /**
     * @return 首页
     */
    @RequestMapping(value = "index.html")
    public String index(Model model){
        model.addAttribute("user",getUser());
        if(getUser().getId()==1){
            return "index";
        }else{
            return "userIndex";
        }

    }

    /**
     * @return 用户管理
     */
    @RequestMapping(value = "user.html")
    public String user(){
        return "user/user";
    }
    /**
     * @return 用户管理添加
     */
    @RequestMapping(value = "user_add.html")
    public String user_add(){
        return "user/user_add";
    }
    /**
     * @return 用户管理编辑
     */
    @RequestMapping(value = "user_edit.html")
    public String user_edit(Model model, Long id) {
        model.addAttribute("user",userService.getById(id));
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",id);
        model.addAttribute("userImage",userImageService.list(queryWrapper));
        return "user/user_edit";
    }
    /**
     * @return 用户管理审核
     */
    @RequestMapping(value = "examine.html")
    public String examine(Model model, Long id) {
        User user = userService.getById(id);
        model.addAttribute("user",user);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",user.getId());
        UserOrder userOrder = userOrderService.getOne(queryWrapper);
        if(userOrder!=null){
            return "user/examine";
        }
        return "pay/noPay";
    }
    /**
     * @return 查看
     */
    @RequestMapping(value = "show.html")
    public String show(Model model, Long id) {
        model.addAttribute("user",userService.getById(id));
        return "user/show";
    }

    /**
     * @return 欢迎页
     */
    @RequestMapping(value = "welcome.html")
    public String welcome(Model model) {
        List<User> ll = new ArrayList<>();
        QueryWrapper queryWrapper =new QueryWrapper();
        queryWrapper.eq("state",2);
        List<User> users = userService.list(queryWrapper);
        for (int i = 0; i < users.size(); i++) {
            if(users.get(i).getId()!=1){
                users.get(i).setMoney(Integer.parseInt(users.get(i).getSettlementFee()));
                ll.add(users.get(i));
            }
        }
        model.addAttribute("user",ll);
        model.addAttribute("money",ll.stream().collect(Collectors.summingInt(User::getMoney)));
        return "welcome";
    }
    /**
     * @return 欢迎页
     */
    @RequestMapping(value = "userWelcome.html")
    public String userWelcome(Model model) {
        model.addAttribute("user",getUser());
        return "welcome/userWelcome";
    }


    /**
     * @return 资料修改
     */
    @RequestMapping(value = "dataUpdate.html")
    public String dataUpdate(Model model){
        model.addAttribute("user",userService.getById(getUser().getId()));
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",getUser().getId());
        model.addAttribute("userImage",userImageService.list(queryWrapper));
        return "user/dataUpdate";
    }



    /**
     * @param
     * @param account
     * @param passWord
     * @return 登陆
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public ApiResult login(String account, String passWord) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(
                account,
                passWord);

        //进行验证，这里可以捕获异常，然后返回对应信息
        try {
            subject.login(token);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("account",account);
            User user = userService.getOne(queryWrapper);
            if(user.getState()==1){
                return ApiResult.fail("该商家未审核,审核后在登陆");
            }else if(user.getState()==2){
                return ApiResult.ok();
            }else{
                return ApiResult.fail("该商家审核失败!");
            }
        }catch (Exception e){
            return ApiResult.fail("请核实账户或密码!");
        }
    }

    /**
     * 登出
     *
     * @return
     */
    @RequestMapping(value = "/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();//取出当前验证主体
        if (subject != null) {
            subject.logout();//不为空，执行一次logout的操作，将session全部清空
        }
        return "login";
    }

    /**
     * @return 出现错误
     */
    @RequestMapping(value = "no.html")
    public String no(){
        return "noUp";
    }

    /**
     * @return 支付成功
     */
    @RequestMapping(value = "paySuccess.html")
    public String paySuccess(){
        return "pay/paySuccess";
    }

    /**
     * @return 支付失败
     */
    @RequestMapping(value = "payFail.html")
    public String payFail(){
        return "pay/payFail";
    }

    /**
     * @return 该订单未审核
     */
    @RequestMapping(value = "noPay.html")
    public String noPay(){
        return "pay/noPay";
    }

    /**
     * @param voPage
     * @return 后台查询
     */
    @RequestMapping(value = "selectMyPage",method = RequestMethod.GET)
    @ResponseBody
    public ResultPage<User> selectMyPage(VoPage voPage, User user){
        return userService.selectMyPage(voPage,user);
    }


    /**
     * @param response
     * @param request
     * @throws AlipayApiException
     * @throws IOException
     * 之支付宝支付
     */
    @RequestMapping(value = "zfbPay")
    public void zfbPay(HttpServletResponse response, HttpServletRequest request,Long id,Model model)throws AlipayApiException, IOException{
        User user = userService.getById(id);
        //如果该商户状态是1 那就是未审核
//        if(user.getState()==1){
//            response.setContentType("text/html;charset=utf-8");
//            response.sendRedirect("/user/payExamine.html");
//        }else{
            try {
                String html = userService.zfbPay(user,request);
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().println(html);
            } catch (CommonException | IOException e)    {
                response.setContentType("text/html;charset=utf-8");
                response.sendRedirect("/user/no.html");
            }
//        }
        //查询该订单是否支付
//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.eq("user_id",user.getId());
//        UserOrder userOrder = userOrderService.getOne(queryWrapper);
//        if(userOrder!=null){
//            response.setContentType("text/html;charset=utf-8");
//            response.sendRedirect("/user/success.html");
//        }

    }


    /**
     * @param user
     * @return 添加
     */
    @RequestMapping(value = "save")
    @ResponseBody
    public ApiResult save(@RequestBody  User user ){
        List<User> users = userService.list();
        for (int i = 0; i < users.size(); i++) {
            if(users.get(i).getAccount().equals(user.getAccount())){
                return ApiResult.fail("该账号已存在!");
            }
        }
        user.setCreateTime(System.currentTimeMillis());
        user.setState(1);
        user.setCharge(1);
        if(userService.save(user)){
            String[] str = user.getDuo().split(";");
            for (int i = 0; i < str.length; i++) {
                UserImage userImage = new UserImage();
                userImage.setId(null);
                userImage.setUrl(str[i]);
                userImage.setUserId(user.getId());
                if(!userImageService.save(userImage)){
                    return ApiResult.fail("添加门头照失败");
                }
            }
        }
        userService.saveRole(user.getId(),user.getAccount());
        return ApiResult.ok();
    }

    /**
     * @param user
     * @return 修改
     */
    @RequestMapping(value = "updateById")
    @ResponseBody
    public ApiResult updateById(@RequestBody User user){
        System.out.printf("sadad:"+user.getDuo());
        List<User> users = userService.list();
        for (int i = 0; i < users.size(); i++) {
            User user1 = users.get(i);
            if(user1.getAccount().equals(user.getAccount())){
                return ApiResult.fail("该账户已存在!");
            }
        }
        if(userService.updateById(user)){
            if(user.getDuo()!=""){
                //查询除商家门头照,先删除在添加进去
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("user_id",user.getId());
                List<UserImage> userImages = userImageService.list(queryWrapper);
                for (int i = 0; i < userImages.size(); i++) {
                    if(!userImageService.removeById(userImages.get(i).getId())){
                        return ApiResult.fail("修改失败");
                    }
                }
                //添加门头照
                String[] str = user.getDuo().split(";");
                for (int i = 0; i < str.length; i++) {
                    UserImage userImage = new UserImage();
                    userImage.setId(null);
                    userImage.setUrl(str[i]);
                    userImage.setUserId(user.getId());
                    if(!userImageService.save(userImage)){
                        return ApiResult.fail("修改门头照失败");
                    }
                }
            }

        }
        return ApiResult.ok();
    }

    /**
     * @param id
     * @return 删除
     */
    @RequestMapping(value = "deleteById")
    @ResponseBody
    public ApiResult deleteById(Long id){
        if(userService.removeById(id)){
            QueryWrapper queryWrapper4 = new QueryWrapper();
            queryWrapper4.eq("user_id",id);
            List<UserImage> userImages = userImageService.list(queryWrapper4);
            for (int i = 0; i < userImages.size(); i++) {
                if(!userImageService.removeById(userImages.get(i))){
                    return ApiResult.fail("删除门头照失败");
                }
            }
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("user_id",id);
            Role role = roleService.getOne(queryWrapper);
            if(roleService.removeById(role.getId())){
                QueryWrapper queryWrapper1 = new QueryWrapper();
                queryWrapper1.eq("role_id",role.getId());
                RoleUser roleUser = roleUserService.getOne(queryWrapper1);
                if(roleUserService.removeById(roleUser.getId())){
                    QueryWrapper queryWrapper2 = new QueryWrapper();
                    queryWrapper2.eq("role_id",roleUser.getRoleId());
                    List<RoleMenu> roleMenus = roleMenuService.list(queryWrapper2);
                    for (int i = 0; i < roleMenus.size(); i++) {
                        if(!roleMenuService.removeById(roleMenus.get(i).getId())){
                            return ApiResult.fail();
                        }
                    }
                }
            }
        }

        return ApiResult.ok();
    }


    /**
     * @param
     * @return 通过
     */
    @RequestMapping(value = "success")
    @ResponseBody
    public ApiResult success(@RequestBody User user) {
        user.setState(2);
        if (userService.updateById(user)) {
            return ApiResult.ok(userService.SendSMSO(user.getPhone(), user.getAccount(), user.getPassWord()));
        }
        return ApiResult.fail();
    }
    /**
     * @param
     * @return 失败
     */
    @RequestMapping(value = "error")
    @ResponseBody
    public ApiResult error(@RequestBody User user) {
        if (userService.removeById(user)) {
            return ApiResult.ok(userService.SendSMSOError(user.getPhone()));
        }
        return ApiResult.fail();
    }

    /**
     * @return 统计所有月分的商家
     */
    @RequestMapping(value = "selectByTimeCount",method = RequestMethod.GET)
    @ResponseBody
    public List selectByTimeCount() throws Exception {
        return userService.selectByTimeCount();
    }





    /**
     * @param user
     * @return 修改状态 (收费不收费)
     */
    @RequestMapping(value = "updateState")
    @ResponseBody
    public ApiResult updateState(@RequestBody User user){
        if(userService.updateById(user)){
            return ApiResult.ok();
        }
        return ApiResult.fail();
    }

    /**
     * @return 统计所有月分的微信用户
     */
    @RequestMapping(value = "selectMoney",method = RequestMethod.GET)
    @ResponseBody
    public List selectMoney() throws Exception {
        return userService.selectMoney();
    }


}
